<template>
  <el-dialog
    @close="closeeditForm"
    title="提示"
    :visible.sync="editdialogVisible"
    width="50%"
  >
    <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="70px"
    >
      <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUsers">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'UserEditDialogo',
  props: {
    editForm: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    //邮箱的验证规则
    var checkEmail = (rule, value, callback) => {
      //定义正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      //验证值
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('输入合法邮箱'))
      }
    }
    //手机的验证规则
    var checkMobile = (rule, value, callback) => {
      //定义正则表达式
      const regMobile =
        /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      //验证值
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('输入合法手机号'))
      }
    }
    return {
      editdialogVisible: false,
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile },
        ],
      },
    }
  },
  methods: {
    closeeditForm() {
      this.$refs.editFormRef.resetFields()
    },
    editUsers() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        if (res.meta.status !== 200) {
          this.$message.error('更新失败')
        } else {
          this.$message.success('更新成功')
          this.$parent.$parent.$parent.getqueryUsers()
          this.editdialogVisible = false
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
</style>